from django.conf import settings
from rest_framework import serializers
from user.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django_redis import get_redis_connection
from .models import OAuthQQUser
from rest_framework_jwt.settings import api_settings

class OauthSerializer(serializers.Serializer):
    mobile = serializers.RegexField(regex='1[3-9]\d{9}')
    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    password = serializers.CharField(max_length=20,min_length=8,write_only=True)
    access_token = serializers.CharField(write_only=True)
    username = serializers.CharField(max_length=20,min_length=6,read_only=True)
    token = serializers.CharField(read_only=True)

    # 先往attrs插入openid
    # 再往attrs插入user绑定用户对象，没绑定就直接返回
    def validate(self, attrs):
        #　1.创建tjs对象
        #　2.解密access_token
        # 3.保存openid在attrs

        tjs = TJS(settings.SECRET_KEY,300)
        try:
            # 解密操作
            data = tjs.loads(attrs['access_token'])
        except:
            raise serializers.ValidationError("access_token有误")
        # 解密还不是完整的openid 获取openid数据
        openid = data.get('openid')

        if not openid:
            raise serializers.ValidationError('access_token失效')

        attrs['openid'] = openid

        # 验证码校验
        conn = get_redis_connection('verify')
        real_sms_code = conn.get('SMScode_%s'%attrs['mobile'])
        if not real_sms_code:
            raise serializers.ValidationError('验证码已过期')
        if real_sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码输入错误')

        try:
            # 该用户已存在
            user = User.objects.get(mobile=attrs['mobile'])
            if user.check_password(attrs['password']):
                attrs['user'] = user
                return attrs
            raise serializers.ValidationError('密码输入错误')

        except:
            # 该用户未注册
            # 表明要创建create用户对象
            return attrs



    # validated_data就是上面的attrs
    def create(self, validated_data):
        # 判断用户是否注册，未注册为None就创建用户
        user = validated_data.get('user',None)

        if user is None:
            user = User.objects.create_user(mobile=validated_data['mobile'],
                                      username=validated_data['mobile'],
                                      password=validated_data['password'],)

        #　用户绑定openid
        OAuthQQUser.objects.create(openid=validated_data['openid'],user=validated_data['user'])


        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        # 向视图对象中补充user对象属性，以便在视图中使用user
        self.context['view'].user = user

        return user


